#!/usr/bin/env python
#coding:utf-8
from mako.lookup import TemplateLookup
import common
import re

#variables
tpls = TemplateLookup(directories=[common.PATH+'/templates'],
					input_encoding='utf-8',
					output_encoding='utf-8')

#functions
def error_page(e=u'出错啦',url='/'):
	html = tpls.get_template('error.html').render(cat=u'出错了',message=e,gotourl=url)
	return html

def jump_page(msg=u'跳转首页中',url='/'):
	cat = u'跳转中'
	html = tpls.get_template('jump.html').render(cat=cat,message=msg,gotourl=url)
	return html

def str2ip(ip):
	if ',' in ip:
		ip = ip[:ip.find(',')]
	ip = ip.split('.')
	ipv4 = 0
	for x in ip[:4]:
		ipv4 = ipv4<<8 | int(x)
	return ipv4

def ip2str(ip):
	return '%s.%s.%s.%s' % (ip>>24,(ip>>16)&0xff,(ip>>8)&0xff,ip&0xff)


def hightlight(q,text):
	for q in q.split('+'):
		if q in ['.','*','?','(',')']:
			q = '\\'+q
		text = re.sub('(?i)('+q+')', r'<font style="BACKGROUND-COLOR: yellow">\1</font>', text)
	return text

def generate_navs(current,total,perpage=common.PERPAGE):
	'''Generate navigation parameters for html templates'''
	cur = current
	records = total
	pages = (total-1)/perpage+1
	navs = []
	prev = cur - 1
	if prev < 1:
		prev = 1
	next = cur + 1
	if next > pages:
		next = pages
	last = pages
	if cur<=4:
		navs = range(1,min(last+1,8))
	elif cur>=last-4:
		navs = range(last-6,last+1)
	else:
		navs = range(cur-3,cur+4)
	return [cur,records,pages,navs,prev,next,last]

def cite(content,parent,c=None):
	if not c:
		c = comon.getdb().cursor()
	c.execute('select cid,username,date,url,content,parent from gb_cmts where cid=%s',(parent,))
	x = c.fetchone()
	if not x:
		return content
	rtn = u'''<ul class="child">'''
	if x[0]%2==0:
		rtn+=u'''<li class="comment even" id="comment-%s">''' % x[0]
	else:
		rtn+=u'''<li class="comment odd" id="comment-%s">''' % x[0]
	rtn += u'''<p><p>%s说道：<p>%s</p></p>''' % (x[1].decode('utf-8'),x[4].decode('utf-8'))
	rtn += u'''</li></ul><p>'''
	rtn += content
	return rtn

def validate_email(email):
	if len(email) > 7:
		if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
			return 1
	return 0
